package history;

import avenue.Session;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import model.Collection;
import model.DBManager;
import model.Station;
import model.Vehicle;

public class IstorikoDieleuseon extends javax.swing.JFrame {

    public IstorikoDieleuseon() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) { 
            em.getTransaction().begin();
        }
        initComponents();
         setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : stationQuery.getResultList();
        appUser = Session.loginUser;
        collectionQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT c FROM Collection c");
        collectionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(collectionQuery.getResultList());
        collectionList.clear();
        cardIdLabel = new javax.swing.JLabel();
        cardIdTF = new javax.swing.JTextField();
        regNumberLabel = new javax.swing.JLabel();
        regNumberTF = new javax.swing.JTextField();
        stationLabel = new javax.swing.JLabel();
        stationComboBox = new javax.swing.JComboBox();
        fromDateLabel = new javax.swing.JLabel();
        fromDateChooser = new com.toedter.calendar.JDateChooser();
        toDateLabel = new javax.swing.JLabel();
        toDateChooser = new com.toedter.calendar.JDateChooser();
        searchButton = new javax.swing.JButton();
        separator = new javax.swing.JSeparator();
        paymentScrollPane = new javax.swing.JScrollPane();
        paymentTable = new javax.swing.JTable();
        returnButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ιστορικό Διελεύσεων");

        cardIdLabel.setText("Αριθμός Κάρτας:");

        regNumberLabel.setText("Αριθμός Κυκλοφορίας:");

        stationLabel.setText("Σταθμός:");

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, stationList, stationComboBox, "stationList");
        bindingGroup.addBinding(jComboBoxBinding);
        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_ONCE, appUser, org.jdesktop.beansbinding.ELProperty.create("${stationId}"), stationComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "station");
        bindingGroup.addBinding(binding);

        fromDateLabel.setText("Από:");

        toDateLabel.setText("Μέχρι:");

        searchButton.setText("Αναζήτηση");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, collectionList, paymentTable, "collectionList");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${passTimestamp}"));
        columnBinding.setColumnName("Pass Timestamp");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.barcode}"));
        columnBinding.setColumnName("Card Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tollCollected}"));
        columnBinding.setColumnName("Toll Collected");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        paymentScrollPane.setViewportView(paymentTable);

        returnButton.setText("Επιστροφή");
        returnButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                returnButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(separator)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(paymentScrollPane)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cardIdLabel)
                                        .addGap(38, 38, 38)
                                        .addComponent(cardIdTF, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(fromDateLabel)
                                        .addGap(18, 18, 18)
                                        .addComponent(fromDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(33, 33, 33)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(toDateLabel)
                                        .addGap(54, 54, 54)
                                        .addComponent(toDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(regNumberLabel)
                                        .addGap(51, 51, 51)
                                        .addComponent(regNumberTF, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                                .addComponent(stationLabel)
                                .addGap(37, 37, 37)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(stationComboBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(searchButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(returnButton)
                .addGap(336, 336, 336))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cardIdLabel)
                        .addComponent(cardIdTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(regNumberLabel)
                        .addComponent(regNumberTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(stationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(stationLabel)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(fromDateLabel)
                    .addComponent(fromDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(toDateLabel)
                    .addComponent(toDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addGap(34, 34, 34)
                .addComponent(separator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(paymentScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(returnButton)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        
        try { 
            
            String cardId = cardIdTF.getText();
            String regNumber = regNumberTF.getText();
            String stationId = ((Station) stationList.get(stationComboBox.getSelectedIndex())).getId().toString();
            Date from;
            try { 
                Calendar fromCal = fromDateChooser.getCalendar();
                fromCal.set(Calendar.HOUR_OF_DAY, 0);
                fromCal.set(Calendar.MINUTE, 0);
                fromCal.set(Calendar.SECOND, 0);
                fromCal.set(Calendar.DAY_OF_YEAR,fromCal.get(Calendar.DAY_OF_YEAR)-1);
                from = fromCal.getTime();
            } catch(Exception ex) { 
                from = null;
            }
            Date to;
            try { 
                Calendar toCal = toDateChooser.getCalendar();
                toCal.set(Calendar.HOUR_OF_DAY, 0);
                toCal.set(Calendar.MINUTE, 0);
                toCal.set(Calendar.SECOND, 0);
                to = toCal.getTime();
            } catch(Exception ex) { 
                to = null;
            }
        
            
            List<Collection> tmpList = collectionQuery.getResultList();
            
            
            for (int i = tmpList.size()-1; i>= 0; i--) {
                 Collection c = tmpList.get(i);
                 boolean remove = false;
                 // Αριθμός κάρτας
                 if (!cardId.equals("")) { 
                     //if (!c.getCardId().getId().toString().equals(cardId)) 
                     if (!String.valueOf(c.getCardId().getBarcode()).equals(cardId))
                     { 
                         remove = true;
                     }
                 }
               
                 if (!regNumber.equals("")) { 
                     for (Vehicle h : c.getCardId().getVehicleList()) { 
                          if (!h.getRegNumber().equals(regNumber)) { 
                              remove = true;
                          }
                     }
                 }
               
                 if (!c.getStationId().getId().toString().equals(stationId)) {
                     remove = true;
                 }
                 
                 if (from != null) {
                     if (!from.before(c.getPassTimestamp())) { 
                         remove = true;
                     }
                 }
                 
                 if (to != null) { 
                     if (!to.after(c.getPassTimestamp())) { 
                         remove = true; 
                     }
                 }
                
                 if (remove) {
                    tmpList.remove(c);
                }
                 
            }
            
           
            for (int i = 1; i < tmpList.size(); i++) { 
                 for (int j = 0; j < tmpList.size() - i; j++) { 
                      if (tmpList.get(j).getPassTimestamp().before(tmpList.get(j+1).getPassTimestamp())) { 
                          Collection tmp = tmpList.get(j);
                          tmpList.set(j, tmpList.get(j+1));
                          tmpList.set(j+1, tmp);
                      }
                 }
            }
            
           
            collectionList.clear();
            for (Collection c : tmpList) { 
                 collectionList.add(c);
            }
            
        } catch(Exception ex) { 
            System.out.println(ex.getMessage());
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void returnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_returnButtonActionPerformed
        // Κλείσιμο του παραθύρου
        dispose();
    }//GEN-LAST:event_returnButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private model.AppUser appUser;
    private javax.swing.JLabel cardIdLabel;
    private javax.swing.JTextField cardIdTF;
    private java.util.List<model.Collection> collectionList;
    private javax.persistence.Query collectionQuery;
    private com.toedter.calendar.JDateChooser fromDateChooser;
    private javax.swing.JLabel fromDateLabel;
    private javax.swing.JScrollPane paymentScrollPane;
    private javax.swing.JTable paymentTable;
    private javax.swing.JLabel regNumberLabel;
    private javax.swing.JTextField regNumberTF;
    private javax.swing.JButton returnButton;
    private javax.swing.JButton searchButton;
    private javax.swing.JSeparator separator;
    private javax.swing.JComboBox stationComboBox;
    private javax.swing.JLabel stationLabel;
    private java.util.List stationList;
    private javax.persistence.Query stationQuery;
    private com.toedter.calendar.JDateChooser toDateChooser;
    private javax.swing.JLabel toDateLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    
}
